import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:myapp/app/data/repository/comm_repository.dart';
import 'package:myapp/app/data/repository/movie_repository.dart';
import 'package:myapp/app/modules/movelist/controllers/move_list_controller.dart';
import 'package:myapp/app/widget/category_tab_layout.dart';
import 'package:myapp/app/widget/movie_grid_layout.dart';
import 'package:myapp/app/widget/slider_banner.dart';

class MoveListView extends StatefulWidget {
  final int position;

  MoveListView(this.position);

  @override
  _MoveListViewState createState() => _MoveListViewState();
}

class _MoveListViewState extends State<MoveListView> {
  late MoveListController _controller;

  _MoveListViewState();

  @override
  void initState() {
    Get.lazyPut<IMovieRepository>(() => MovieRepository());
    Get.lazyPut<ICommRepository>(() => CommRepository());
    _controller = MoveListController();
    _controller.requestBannerList();
    _controller.requestCategoryList();
    _controller.requestMovieList();
    super.initState();
  }

  Widget _emptyBanner() {
    return Container(
      margin: EdgeInsets.only(top: 20),
      child: AspectRatio(
        aspectRatio: 16.0 / 6,
        child: Container(
          margin: EdgeInsets.only(left: 16, right: 16),
        ),
      ),
    );
  }

  Obx _buildCategory() {
    return Obx(
      () => _controller.categoryList.isEmpty
          ? Container()
          : Container(
              margin: EdgeInsets.only(left: 16, top: 20),
              child: CategoryTabLayout(
                _controller.categoryList,
                onTab: (index) => {},
              ),
            ),
    );
  }

  Widget _buildMovieList() {
    return Obx(() => ListView.builder(
          shrinkWrap: true,
          physics: NeverScrollableScrollPhysics(),
          itemCount: _controller.movies.length,
          itemBuilder: (context, index) {
            var m = _controller.movies[index];
            return MovieGridLayout(
              m.keys.first,
              m.values.first,
              margin: EdgeInsets.symmetric(horizontal: 16, vertical: 20),
            );
          },
        ));
  }

  @override
  Widget build(BuildContext context) {
    print("_MoveListViewState ${widget.position}");

    return GetBuilder<MoveListController>(
      builder: (controller) {
        return SingleChildScrollView(child: Container(
          child: Column(
            children: [
              Obx(() => _controller.bannerList.isEmpty
                  ? _emptyBanner()
                  : Container(
                margin: EdgeInsets.only(top: 20),
                child: SliderBanner(_controller.bannerList
                    .map((element) => element.img)
                    .toList()),
              )),
              _buildCategory(),
              _buildMovieList()
            ],
          ),
        ),);
      },
      init: _controller,
    );
  }
}
